<?php


namespace app\api\logic;


use app\api\model\Category as CategoryModel;
use app\api\model\Code as CodeModel;
use app\api\model\Merchant as MerchantModel;
use app\api\model\Posts as PostsModel;
use app\api\model\Airport as AirportModel;
use app\api\model\Area as AreaModel;
use think\facade\Cache;
use think\facade\Session;

class Merchant
{
    private  $merchantID;
    private  $merchantType;
    private  $jti;
    private  $iat;
    private $merchantModel;
    private $postsModel;

    public function __construct(MerchantModel $merchantModel,PostsModel $postsModel)
    {
        $this->merchantID=Session::get('userId');
        $this->merchantType=Session::get('userType');
        $this->jti=Session::get('jti');
        $this->iat=Session::get('iat');
        $this->merchantModel=$merchantModel;
        $this->postsModel=$postsModel;
    }

    public function index($id){
        $info=$this->merchantModel->info($id);
        if(empty($info)) return false;
        $banner_images=[];
        if($info['images']){
            $images=json_decode($info['images']);
            foreach ($images as $image){
                $banner_images[]=get_file_path($image);
            }
        }
        $info['images']=$banner_images;
        $week=json_decode($info['week'],true);
        $info['week']=$week;
        $info['avatar']=getMerchantAvatar($info['avatar']);
//        $info['header_image']='';
        if($info['header_image']) {
            $info['header_image']=get_file_path($info['header_image']);
        }
        if($info['category']){
            $info['category_id']=$info['category'];
            $info['category']=CategoryModel::where('id',$info['category'])->value('name');
        }
        $sub_categories=[];
        if($info['sub_category']){
            $sub_category=explode(',',$info['sub_category']);

            foreach ($sub_category as $k=>$v){
                $sub_categories[$k]['name']=CategoryModel::where('id',$v)->value('name');
                $sub_categories[$k]['id']=intval($v);
            }
        }
        $info['sub_category']=$sub_categories;
        return $info;
    }

    public function login($data){
        //验证验证码
        if($data['type']==1){
            $res=Common::checkCode($data,config('data.code_type.login'),config('data.role_type.merchant'));
            if($res['req']==0){
                return $res;
            }
        }
        $result=[];
        $info=MerchantModel::where(['account'=>$data['email']])->where('status','neq',-1)->field('account,name,id,salt,password,status,country,city,airport,avatar')->find();
        if(empty($info)){
            if($data['type']==1){
                //去注册
                //$result=self::register($data);
                $result['scene']=2; //注册场景
                $result['req']=1;
            }else{
                $result['req']=0;
                $result['msg']='Account or password error';
            }
        }else{
            if($data['type']==2){
                //验证密码
                if($info['password']!=sha1($info['salt'].$data['password'])){
                    $result['req']=0;
                    $result['msg']='Account or password error';
                    return $result;
                }
            }
            //验证状态
            if($info['status']==-1){
                $result['req']=0;
                $result['msg']='The current user has been logged out';
                return $result;
            }
            $result=$this->getUserInfo($info);
        }
        return $result;
    }

    private function getUserInfo($info){
        $airportInfo=AirportModel::where('id',$info['airport'])->field('iata,country,city,terminal')->find()->toArray();
        $userInfo=$airportInfo;
//        $userInfo['iata']=AirportModel::where('id',$info['airport'])->value('iata');
        $userInfo['country_name']=AreaModel::where('id',$airportInfo['country'])->value('name');
        $userInfo['abbreviation_name']=AreaModel::where('id',$airportInfo['country'])->value('abbreviation');
        $userInfo['city_name']=AreaModel::where('id',$airportInfo['city'])->value('name');
        //获取登录信息
        $result['scene']=1; //登录场景
        $result['req']=1;
        $result['id']=$info['id'];
//        $result['username']=$info['name'];
        $result['country']=$info['country'];
        $result['country_name']=$userInfo['country_name'];
        $result['city']=$userInfo['city'];
        $result['city_name']=$userInfo['city_name'];
        $result['abbreviation']=$userInfo['abbreviation_name'];
        $result['airport_id']=$info['airport'];
        $result['iata']=$userInfo['iata'];
        $result['terminal']=json_decode($airportInfo['terminal'],true);
        //获取用户头像
        if(!isset($info['avatar']) || !$info['avatar']){
            $result['avatar']=get_file_path(config('data.merchant_avatar_default'));
        }else{
            $result['avatar']=get_file_path($info['avatar']);
        }
        Session::clear();
        Session::set('userId',$info['id']);
//        Session::set('userName',$info['name']);
        Session::set('userType',config('data.role_type.merchant'));
        Session::set('country',$info['country']);
        return $result;
    }

    public function logoff($data){
        //校验验证码
        $type=$this->merchantType;

        $res=Common::checkCode($data,config('data.code_type.logoff'),$type);
        if($res['req']==0){
            return $res;
        }
        //校验手机号是否匹配
        $merchant_email=MerchantModel::where(['id'=>$this->merchantID])->value('email');
        if($merchant_email!=$data['email']){
            $result['req']=0;
            $result['msg']='The current email does not match the email';
            return $result;
        }

        MerchantModel::update(['status'=>-1],['id'=>$this->merchantID]);
        $res['req']=1;
        return $res;
    }

    public function logout(){
        $handler=Cache::store('redis')->handler();
        $key='MERCHANT:'.$this->iat.':'.$this->merchantID;
        $handler->set($key,$this->jti,config('jwt.access_token_expire'));
        Session::delete('userId');
        Session::delete('userName');
        Session::delete('userType');
        Session::delete('jti');
        Session::delete('iat');
        return true;
    }

    public function complete($data){
        $merchantModel=new MerchantModel();
        $salt=salt();
        $data['salt']=$salt;
        $data['account']=$data['email'];
        $data['password']=sha1($salt.$data['password']);
        $data['create_time']=date('Y-m-d H:i:s');

        if(isset($data['week']) && $data['week']){
            $data['week']=json_encode(explode(',',$data['week']));
        }else{
            $data['week']=json_encode([]);
        }


        //轮播图上传
        if(isset($data['images']) && $data['images']){
            $data['images']=json_encode(explode(',',$data['images']));
        }else{
            $data['images']=json_encode([]);
        }

        if(empty($data['end_time'])){
            $data['end_time']='23:59:00';
        }

//        if(isset($data['week']) && isset($data['start_time'])){
//            $localArr=handleOpenTime($data['week'],$data['start_time'],$data['end_time'],Session::get('country'));
//            $data['base_week']=$localArr['week'];
//            $data['base_start_time']=$localArr['start_time'];
//            $data['base_end_time']=$localArr['end_time'];
//        }
        $flag=$merchantModel->complete($data);
        if($flag){
            $data['id']=$flag;
            //自动登录
            return $this->getUserInfo($data);
        }else{
            return false;
        }
    }


    public function edit($data){
        $merchantModel=new MerchantModel();
        $data['id']=$this->merchantID;
        //获取商户状态
        $status=$merchantModel->where('id',$data['id'])->value('status');
        if($status<1) return false;
        if(isset($data['week']) && $data['week']){
            $data['week']=json_encode(explode(',',$data['week']));
        }else{
            $data['week']=json_encode([]);
        }
        
        //轮播图上传
        if(isset($data['images']) && $data['images']){
            $data['images']=json_encode(explode(',',$data['images']));
        }else{
            $data['images']=json_encode([]);
        }
        return $merchantModel->complete($data,2);
    }

    public function update($data){
        return MerchantModel::update($data,['id'=>$this->merchantID]);
    }

    public function getInfo($where,$field){
        $res=MerchantModel::where($where)->where('status','<>','-1')->field($field)->find();
        if($res){
            return $res->toArray();
        }
        return $res;
    }
}

